import { Button, Form, Input, Table, Tag, Space, Flex } from 'antd'
import { useEffect, useState, useCallback } from 'react'
import { findAllUser, deleteUser, updateUser, resetUserPassword } from '@/api/user'
import { useSelector } from 'react-redux'
import UserForm from './UserForm'
import useConfirmModal from '@/hooks/useConfirmModal'
import FormButton from '@/components/formButton'
import md5 from 'md5'

const User = () => {
  const dictionary = useSelector((state) => state.data.dictionary)
  const [dataSource, setDataSource] = useState([])
  const [userModalVisible, setUserModalVisible] = useState(false)
  const [modalTitle, setModalTitle] = useState('')
  const [userId, setUserId] = useState('')
  const confirmModal = useConfirmModal()

  const handleOpenModal = (title, user_id) => {
    setModalTitle(title)
    setUserId(user_id)
    setUserModalVisible(true)
  }

  const getUserList = useCallback(async () => {
    const { data } = await findAllUser()
    setDataSource(data)
  }, [])

  const handleDeleteUser = (user_id) => {
    confirmModal(async () => {
      await deleteUser({ user_id })
      getUserList()
    })
  }

  const updateUserStatus = async (id, status) => {
    await updateUser({ id, status })
    getUserList()
  }

  const resetPassword = async (id) => {
    confirmModal(async () => {
      await resetUserPassword({
        user_id: id,
        password: md5('123456')
      })
      getUserList()
    })
  }

  useEffect(() => {
    getUserList()
  }, [getUserList])

  const columns = [
    {
      title: '序号',
      dataIndex: 'user_id',
      width: 50,
      align: 'center',
      render: (text, record, index) => {
        return index + 1
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
      align: 'center'
    },
    {
      title: '性别',
      dataIndex: 'gender',
      align: 'center',
      render: (text) => {
        return dictionary?.gender.data[text]?.label
      }
    },
    {
      title: '手机号',
      dataIndex: 'phone_number',
      align: 'center'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      align: 'center'
    },
    {
      title: '角色',
      dataIndex: 'role',
      align: 'center',
      render: (text) => {
        const find = dictionary?.role.data.find(item => item.value === text)
        return <Tag color='success'>{find?.label}</Tag>
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      render: (text) => {
        const color = text === 1 ? 'success' : 'error'
        return <Tag color={color}>{dictionary?.status.data[text]?.label}</Tag>
      }
    },
    {
      title: '操作',
      fixed: 'right',
      width: 260,
      align: 'center',
      render: (text, record) => {
        const { user_id, status } = record
        return <Flex gap="small" justify="center">
          <Button color="blue" variant='filled' size="small" onClick={() => handleOpenModal('编辑用户', user_id)}>编辑</Button>
          <Button color="red" variant='filled' size="small" onClick={() => handleDeleteUser(user_id)}>删除</Button>
          <Button color="green" variant='filled' size="small" onClick={() => handleOpenModal('用户详情', user_id)}>详情</Button>
          { status === 0 && <Button color="orange" variant='filled' onClick={() => updateUserStatus(user_id, 1)} size="small">启用</Button> }
          { status === 1 && <Button color="gray" variant='filled' onClick={() => updateUserStatus(user_id, 0)} size="small">禁用</Button> }
          <Button color="blue" variant='filled' disabled={status === 0} onClick={() => resetPassword(user_id, 0)} size="small">重置密码</Button>
        </Flex>
      }
    }
  ]

  const onFinish = (values) => {
    console.log('Success:', values)
  }

  const onOk = () => {
    getUserList()
    setUserModalVisible(false)
  }

  const exportData = () => {
    console.log('导出')
  }

  const importData = () => {
    console.log('导入')
  }

  const downloadData = () => {
    console.log('下载')
  }

  return <>
    <div>
      <Space direction="vertical" size="middle">
        <Form layout="inline" onFinish={onFinish}>
          <Form.Item
            label="用户名"
            name="username"
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item>
            <FormButton
              search={getUserList}
              add={() => handleOpenModal('新增用户')}
              export={exportData}
              import={importData}
              download={downloadData}
            />
          </Form.Item>
        </Form>

        <Table
          bordered
          columns={columns}
          dataSource={dataSource}
          rowKey="user_id"
          size="small"
          scroll={{ x: 'max-content' }}
        />
      </Space>

      {
        userModalVisible &&
        <UserForm
          title={modalTitle}
          user_id={userId}
          visible={userModalVisible}
          onCancel={() => setUserModalVisible(false)}
          onOk={onOk}
        />
      }
    </div>
  </>
}

export default User